package cn.rjzjh.tapestry.tams.base;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.apache.tapestry5.util.TextStreamResponse;
import cn.rjzjh.commons.util.apiext.DateUtil;
import cn.rjzjh.commons.util.apiext.NumberUtil;
import cn.rjzjh.commons.util.apiext.StringUtil;
import cn.rjzjh.commons.util.callback.IConvertValue;
import cn.rjzjh.commons.util.web.EasyUiAssist;
import cn.rjzjh.commons.util.web.OperateResult;
import cn.rjzjh.tapestry.busi.convert.ConvertValueOpt;
import cn.rjzjh.tapestry.component.services.ISupportedLocales;
import cn.rjzjh.tapestry.component.tools.TapestryAssist;
import cn.rjzjh.tapestry.component.tools.convert.ConvertValueEnum;
import cn.rjzjh.tapestry.hibernate.services.IHbService;

@SuppressWarnings("rawtypes")
public abstract class ParentPage {
	// private static Logger logger = LoggerFactory.getLogger(ParentPage.class);

	@InjectService("locales")
	protected ISupportedLocales supportedLocales;

	@Inject
	protected Request request;

	@Inject
	protected RequestGlobals requestGlobals;

	@Inject
	protected Messages messages;// 国际化

	@Environmental
	protected JavaScriptSupport javaScriptSupport;

	@Inject
	@Symbol(SymbolConstants.CONTEXT_PATH)
	@Property
	protected String contextPath;

	@Inject
	protected IHbService hbService;

	@Property
	protected String lan = supportedLocales.getCurLocale().getLanguage();// 当前选择语言

	/****
	 * 国际化方法　可以把数据库取出来的值进行国际化 eg:${L('order.channel')}
	 *
	 * @param path
	 *            要国际化的值所在的路径　
	 * @return
	 */
	public String L(String path) {
		try {
			Object obj = PropertyUtils.getProperty(this, path);
			String objkey = String.valueOf(obj);
			if (StringUtil.isNull(objkey)) {
				return "";
			}
			return messages.get(objkey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return path;
	}

	/****
	 * 对具的key值进行国际化，可以支持传参数,eg:${LK('Tmall',['aaa','bbb'])}
	 *
	 * @param key
	 *            国际化的key值
	 * @param param
	 *            　所带的参数
	 * @return
	 */
	public String LK(String key, Object... param) {
		return TapestryAssist.LK(messages, key, param);
	}

	/***
	 * 把某个时间字段格式化为yyyy-MM-dd HH:mm:ss
	 *
	 * @param path
	 *            要格式化的值所在的路径　
	 * @return
	 */
	public String T(String path) {
		return DateUtil.formatDate(this, path, null, true);
	}

	/****
	 * 把某个时间字段格式化为yyyy-MM-dd
	 *
	 * @param path
	 *            要格式化的值所在的路径　
	 * @return
	 */
	public String D(String path) {
		return DateUtil.formatDate(this, path, null, false);
	}

	/****
	 * 金钱格式化
	 *
	 * @param path
	 * @return
	 */
	public String M(String value) {
		if (StringUtil.isNull(value)) {
			return "";
		}
		try {
			BigDecimal retObj = NumberUtil.handleScale(value, 2);
			return String.valueOf(retObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	protected final IConvertValue I18NConvert = new IConvertValue() {
		@Override
		public String getStr(String key) {
			if (StringUtil.isNull(key) || !messages.contains(key)) {
				return key;
			}
			return messages.get(key);
		}
	};

	/***
	 * 此处如果没有缓存将非常慢 optionItem的国际化解析
	 */
	protected final IConvertValue optConvert = new ConvertValueOpt(
			supportedLocales);

	/****
	 * 支持国际化 的grid
	 *
	 * @param fromList
	 * @param titles
	 * @param recordNum
	 * @param convertTitles
	 *            需要国际化的列会新增一列，规则为 列名+1
	 * @return
	 */
	protected final String getJsonForGridForI18n(List<?> fromList,
			String[] titles, long recordNum, String... convertTitles) {
		IConvertValue[] convert = null;
		if (ArrayUtils.isNotEmpty(convertTitles)) {
			// titles=org.apache.commons.lang3.ArrayUtils.addAll(titles,
			// convertTitles);
			convert = new IConvertValue[titles.length + convertTitles.length];
			for (int i = 0; i < convertTitles.length; i++) {
				String title1 = String.format("%s,%s", convertTitles[i],
						convertTitles[i] + "1");
				org.apache.commons.lang3.ArrayUtils.add(titles, title1);
				convert[titles.length + i] = I18NConvert;
			}
		}
		return EasyUiAssist
				.getJsonForGrid(fromList, titles, convert, recordNum);
	}

	/****
	 * 支持国际化的grid
	 *
	 * @param fromList
	 * @param recordNum
	 * @param convertTitles
	 *            需要国际化的列会新增一列，规则为 列名+1
	 * @return
	 */
	protected final String getJsonForGridAliasForI18n(List<?> fromList,
			long recordNum, String... convertTitles) {
		if (ArrayUtils.isNotEmpty(convertTitles)) {
			Map<String, IConvertValue> convertsMap = new HashMap<String, IConvertValue>();
			String[] alisAry = new String[convertTitles.length];
			for (int i = 0; i < convertTitles.length; i++) {
				String title = convertTitles[i];
				String titleAlis = title + "1";
				alisAry[i] = String.format("%s,%s", title, titleAlis);
				convertsMap.put(titleAlis, I18NConvert);
			}
			return EasyUiAssist.getJsonForGridAlias(fromList, alisAry,
					convertsMap, recordNum);
		} else {
			return EasyUiAssist.getJsonForGridAlias(fromList, recordNum);
		}
	}

	/****
	 * 把指定的Str作为流返回
	 *
	 * @param str
	 * @return
	 */
	protected TextStreamResponse retStream(String str) {
		return TapestryAssist.getTextStreamResponse(str);
	}

	/***
	 * 返回空的grid数据流
	 *
	 * @return
	 */
	protected TextStreamResponse retStreamEmpty() {
		return retStream(EasyUiAssist.getJsonForGridEmpty());
	}

	/****
	 * 通过枚举类构建Easyui的下拉列表
	 *
	 * @return
	 * @throws Exception
	 */
	protected TextStreamResponse onList(String name) throws Exception {
		return retStream(TapestryAssist.buildList(name, messages));
	}

	/***
	 * 得到枚举型的转换器
	 *
	 * @param entityClass
	 * @return
	 */
	protected IConvertValue proEnumConvert(Class entityClass) {
		return new ConvertValueEnum(entityClass, messages);
	}

	protected TextStreamResponse retSuccInfo() {
		return TapestryAssist.getTextStreamResponse(new OperateResult(1,
				"common.hint.success"), I18NConvert);
	}

	protected TextStreamResponse retErrorInfo() {
		return retErrorInfo(null);
	}

	protected TextStreamResponse retErrorInfo(String errmsg) {
		if (StringUtil.isNull(errmsg)) {
			errmsg = "common.hint.error";
		}
		return TapestryAssist.getTextStreamResponse(
				new OperateResult(0, errmsg), I18NConvert);
	}

	/****
	 * 如 itemName 返回 "itemName_zh,itemName"
	 *
	 * @param colName
	 * @return
	 */
	public String getColLan(String colName) {
		String lan = supportedLocales.getCurLocale().getLanguage()
				.substring(0, 1).toUpperCase()
				+ supportedLocales.getCurLocale().getLanguage().substring(1);
		return String.format("%s%s,%s", colName, lan, colName);
	}

}
